package vip.xiaonuo.biz.modular.simple.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.utils.AuthUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.core.cacheentity.Modules;
import vip.xiaonuo.biz.core.eyesnetty.EyesBootNettyClient;
import vip.xiaonuo.biz.core.netty.BootNettyClient;
import vip.xiaonuo.biz.modular.checkdata.entity.SCheckData;
import vip.xiaonuo.biz.modular.checkdata.service.SCheckDataService;
import vip.xiaonuo.biz.modular.eyesdata.entity.SEyesData;
import vip.xiaonuo.biz.modular.eyesdata.service.SEyesDataService;
import vip.xiaonuo.biz.modular.facedata.entity.SFaceData;
import vip.xiaonuo.biz.modular.facedata.service.SFaceDataService;
import vip.xiaonuo.biz.modular.ringdata.entity.SRingData;
import vip.xiaonuo.biz.modular.ringdata.service.SRingDataService;
import vip.xiaonuo.biz.modular.simple.domain.RingPPG;
import vip.xiaonuo.biz.modular.simple.ringUtil;
import vip.xiaonuo.biz.modular.task.entity.STask;
import vip.xiaonuo.biz.modular.task.param.STaskAddParam;
import vip.xiaonuo.biz.modular.task.service.STaskService;
import vip.xiaonuo.biz.modular.taskdata.param.STaskDataAddParam;
import vip.xiaonuo.biz.modular.taskdata.service.STaskDataService;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.biz.websocket.WebSocketServerHandler;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.CommonResponseUtil;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "首页业务控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 4)
@RestController
public class HomeController {

    @Autowired
    private CommonCacheOperator commonCacheOperator;

    @Autowired
    private BootNettyClient faceClient;

    @Autowired
    private EyesBootNettyClient eyesClient;

    @Autowired
    private ringUtil ru;

    @Autowired
    private STaskService sTaskService;

    @Autowired
    private STaskDataService sTaskDataService;


    @Autowired
    private SFaceDataService faceDataService;

    @Autowired
    private SCheckDataService checkDataService;

    @Autowired
    private SRingDataService sRingDataService;


    @PostConstruct
    public void init() {
        initstart();
    }

    public static void main(String[] args) {
        String s = "1716341887 0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.6@8.6,0@0@0@0@-4.5@8.6,0@0@0@0@-4.6@8.6& &0.64,0.64,0.64,0.64&140.2,140.3,141.5,142.7,143.1,144.6,145.1,145.1,146.1,146.2,146.9,146.6,146.9,147,147,146.9,147,146.7,146.6,146.7,146.1,146.1,147.1,147.6,148.8& &78 &33.8@34.1&1003.5&31.8&41.3&";
        String replace = s.replace("\\[", "").replace("]", "");
        String[] split2 = replace.split("&");
        String[] split3 = split2[3].split(",");
        System.out.println(split2[5]);

    }

    @PostConstruct
    public void webSocketAdd() {
        new Thread(() -> {
            while (true) {
                try {
                    Object o = commonCacheOperator.get(Modules.HEARTLIST);
                    JSONArray objects = JSONUtil.parseArray(o);
                    //objects.add(ringUtil.generateRandomDecimal(80, 100));
                    if (objects.size() > 100) {
                        objects.remove(0);
                    }
                    commonCacheOperator.put(Modules.HEARTLIST, objects);
                    JSONObject json = new JSONObject();
                    Object o1 = commonCacheOperator.get("ringTime");
                    long l = Long.parseLong(o1.toString());
                    if (System.currentTimeMillis() - l > 5000) {
                        commonCacheOperator.put(Modules.RING, "0");
                    }
                    if (System.currentTimeMillis() - l < 5000) {
                        commonCacheOperator.put(Modules.RING, "1");
                    }
                    //三个数据状态
                    Object eyes = commonCacheOperator.get(Modules.EYES);
                    Object ring = commonCacheOperator.get(Modules.RING);
                    Object face = commonCacheOperator.get(Modules.FACE);
                    json.put("eyes", Integer.parseInt(eyes.toString()));
                    json.put("ring", Integer.parseInt(ring.toString()));
                    json.put("face", Integer.parseInt(face.toString()));
                    //眨眼频率
                    Object blinkRate = commonCacheOperator.get(Modules.BLINKRATE);
                    //闭合眼时间比例
                    Object blinkTIMERate = commonCacheOperator.get(Modules.BLINKTIMERATE);
                    //时间总长 1分钟
                    Object blinkTimeTatol = commonCacheOperator.get(Modules.BLINKTIMETOTAL);
                    json.put("blinkRate", blinkRate);
                    json.put("blinkTIMERate", blinkTIMERate);
                    json.put("blinkTimeTatol", blinkTimeTatol);
                    //哈欠
                    Object nodRate = commonCacheOperator.get(Modules.NODTIMERATE);
                    //点头
                    Object yawnRate = commonCacheOperator.get(Modules.YAWNTIMERATE);

                    //心电数据
                    json.put("heartList", commonCacheOperator.get(Modules.HEARTLIST));
                    json.put("nodRate", nodRate);
                    json.put("yawnRate", yawnRate);
                    json.put("faceAlarmResourt", String.valueOf(commonCacheOperator.get(Modules.FACEALARMRESOURT)));
                    json.put("ringAlarmResourt", String.valueOf(commonCacheOperator.get(Modules.RINGALARMRESOURT)));
                    json.put("eyesAlarmResourt", String.valueOf(commonCacheOperator.get(Modules.EYESALARMRESOURT)));
                    //脱岗次数
                    json.put("demobilized_time", String.valueOf(commonCacheOperator.get(Modules.FACEDEMOBILIZEDTIME)));
                    //最长时间
                    json.put("demobilizedMAX", commonCacheOperator.get(Modules.FACEDEMOBILIZEDMAX));
                    //离岗次数
                    json.put("demobilized_time", commonCacheOperator.get(Modules.FACEDEMOBILIZEDTIME));
                    //走神次数
                    json.put("eyeletCount", commonCacheOperator.get(Modules.eyeletCount));
                    //走神最长时间
                    //commonCacheOperator.put(Modules.eyeletTimeMin,0);
                    json.put("eyeletTimeMin", commonCacheOperator.get(Modules.eyeletTimeMin));
                   /* if(String.valueOf(commonCacheOperator.get(Modules.EYES)).equals("1")){
                        commonCacheOperator.put(Modules.EYESALARMRESOURT,ringUtil.generateRandomDecimal(0, 100));
                    }else{
                        commonCacheOperator.put(Modules.EYESALARMRESOURT,0);
                    }*/
                    Double total = Double.parseDouble(commonCacheOperator.get(Modules.EYESALARMRESOURT).toString())
                            + Double.parseDouble(commonCacheOperator.get(Modules.RINGALARMRESOURT).toString())
                            + Double.parseDouble(commonCacheOperator.get(Modules.FACEALARMRESOURT).toString());
                    commonCacheOperator.put(Modules.score, String.format("%.2f", total / 3));
                    json.put("score", commonCacheOperator.get(Modules.score));

                    //commonCacheOperator.put("eyesClose15time",0);
                    Object o4 = commonCacheOperator.get("eyesClose15time");
                    Object o2 = commonCacheOperator.get(Modules.YAWNLISTLOW);
                    Object o3 = commonCacheOperator.get(Modules.YAWNLISTHIGHT);
                    int YAWNLISTLOWSize = JSONUtil.parseObj(o2).size();
                    int YAWNLISTHIGHTSize = JSONUtil.parseObj(o3).size();
                    int yawnCount = Integer.parseInt(yawnRate.toString());
                    int eyesClose15timeSize = JSONUtil.parseObj(o4).size();

                    json.put("alarm", 5);
                    if(commonCacheOperator.get(Modules.ALARMTYPE).toString().equals("0")){
                        double blinkTIMERateValue = Double.parseDouble(blinkTIMERate.toString());
                        if (YAWNLISTLOWSize == 0 || blinkTIMERateValue <= 0.075D) {
                            json.put("alarm", 5);
                        }
                        if (YAWNLISTLOWSize == 1 || (blinkTIMERateValue > 0.075 && blinkTIMERateValue <= 0.15D)) {
                            System.out.println("浅哈欠 == 2");
                            json.put("alarm", 4);
                        }
                        if (YAWNLISTLOWSize >= 2 || (blinkTIMERateValue > 0.15 && blinkTIMERateValue <= 0.25D)) {
                            System.out.println("浅哈欠 >= 2");
                            json.put("alarm", 3);
                        }
                        if (YAWNLISTHIGHTSize == 2 || blinkTIMERateValue >= 0.25D) {
                            System.out.println("深哈欠 == 2");
                            json.put("alarm", 2);
                        }
                        if (YAWNLISTHIGHTSize >= 3) {
                            System.out.println("深哈欠 >=3");
                            json.put("alarm", 1);
                        }
                        if (System.currentTimeMillis() - Long.parseLong(o4.toString()) >= 60000) {
                            //System.out.println("闭眼超过15s等级1" );
                            json.put("alarm", 1);
                        }
                    }
                    //type为1的时候是面部识别
                    try{
                        if(commonCacheOperator.get(Modules.ALARMTYPE).toString().equals("1")){
                            JSONObject entries = new JSONObject();
                            entries.putOnce("type","PPG");
                            entries.putOnce("ring",new ArrayList<>());
                            entries.putOnce("face",commonCacheOperator.get("facePythonList"));
                            entries.putOnce("freq",50);
                            String resp = HttpRequest.post("http://127.0.0.1:5000/get")
                                    .header(Header.CONTENT_TYPE, "application/json")
                                    .body(entries.toString())
                                    .execute().body();
                            if(resp.contains("0")){
                                json.put("alarm", 0);
                            }
                            if(resp.contains("1")){
                                json.put("alarm", 1);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                   /* Random random = new Random();
                    int randomNumber = random.nextInt(5) + 1; //
                    json.put("alarm", randomNumber);*/
                    WebSocketServerHandler.SendMessage(json.toString());
                    if (String.valueOf(commonCacheOperator.get(Modules.CHECKSTATUS)).equals(Modules.ON)) {
                        SCheckData sCheckData = new SCheckData();
                        sCheckData.setCheckId(Long.parseLong(commonCacheOperator.get(Modules.TASKID).toString()));
                        sCheckData.setData(json.toString());
                        sCheckData.setUserId(Long.parseLong(commonCacheOperator.get(Modules.USERID).toString()));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String formattedTime = sdf.format(new Date());
                        sCheckData.setTime(formattedTime);
                        checkDataService.save(sCheckData);
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    //e.printStackTrace();
                }
            }

        }).start();
    }
    //commonCacheOperator.put("facePythonList", facePythonList);

    @PostConstruct
    public void dataRef() {
        commonCacheOperator.put(Modules.ALARMTYPE, "0");
        new Thread(() -> {
            while (true) {
                long time = System.currentTimeMillis();
                Object yawnObj = commonCacheOperator.get(Modules.YAWNLIST);
                Object nodObj = commonCacheOperator.get(Modules.NODLIST);
                JSONArray nodArr = JSONUtil.parseArray(nodObj);
                JSONArray yawnArr = JSONUtil.parseArray(yawnObj);
                List<Long> timeOut = new ArrayList<>();
                for (Object object : yawnArr) {
                    long l = Long.parseLong(object.toString());
                    System.out.println("L：" + l);
                    System.out.println(time + " - 60000：" + (time - 60000));
                    if (l <= time - 60000) {
                        timeOut.add(l);
                    }
                }
                for (Long l : timeOut) {
                    yawnArr.remove(l);
                }
                commonCacheOperator.put(Modules.YAWNLIST, yawnArr);
                List<Long> timeOut1 = new ArrayList<>();
                for (Object object : nodArr) {
                    long l = Long.parseLong(object.toString());
                    if (l <= time - 60000) {
                        timeOut1.add(l);
                    }
                }
                for (Long l : timeOut1) {
                    nodArr.remove(l);
                }
                commonCacheOperator.put(Modules.NODLIST, nodArr);
                commonCacheOperator.put(Modules.NODTIMERATE, nodArr.size());
                commonCacheOperator.put(Modules.YAWNTIMERATE, yawnArr.size());
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
    }


    @ApiOperationSupport(order = 1)
    @ApiOperation("开始实时监测")
    @GetMapping("/biz/home/start")
    public CommonResult<String> homeStart() {
        commonCacheOperator.put(Modules.CHECKSTATUS, Modules.ON);
        return CommonResult.ok();
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation("开始实时监测")
    @GetMapping("/biz/home/type")
    public CommonResult<String> type(@RequestParam Integer type) {
        commonCacheOperator.put(Modules.ALARMTYPE, type);
        return CommonResult.ok();
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation("关闭实时监测")
    @GetMapping("/biz/home/stop")
    public CommonResult<String> homeStop() {
        commonCacheOperator.put(Modules.CHECKSTATUS, Modules.OFF);
        return CommonResult.ok();
    }


    @ApiOperationSupport(order = 1)
    @ApiOperation("信息模块状态")
    @GetMapping("/biz/home/deviceStatus")
    public CommonResult<JSONObject> deviceStatus() {
        Object eye = commonCacheOperator.get(Modules.EYES);
        Object ring = commonCacheOperator.get(Modules.RING);
        Object face = commonCacheOperator.get(Modules.FACE);
        JSONObject respJson = new JSONObject();
        respJson.putOnce("eye", eye);
        respJson.putOnce("ring", ring);
        respJson.putOnce("face", face);
        return CommonResult.data(respJson);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation("开启实时数据获取")
    @GetMapping("/biz/home/realTimeData")
    public CommonResult<String> realTime() {
        if (String.valueOf(commonCacheOperator.get(Modules.CHECKSTATUS)).equals(Modules.ON)) {
            return CommonResult.error("任务正在进行中,请先取消");
        }
        initstart();
        commonCacheOperator.put(Modules.CHECKSTATUS, Modules.ON);
        commonCacheOperator.put(Modules.HEARTLIST, new JSONArray());
        faceClient.opean();
        eyesClient.opean();
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        STaskAddParam sTaskAddParam = new STaskAddParam();
        String taskName = UUID.randomUUID().toString();
        sTaskAddParam.setTaskName(taskName);
        sTaskAddParam.setTime(new Date());
        sTaskAddParam.setUserId(loginUser.getId());
        sTaskAddParam.setUserName(loginUser.getName());
        STask sTask = new STask();
        sTask.setTaskName(taskName);
        sTask.setTime(new Date());
        sTask.setUserId(loginUser.getId());
        sTask.setUserName(loginUser.getName());
        sTaskService.save(sTask);
        QueryWrapper<STask> qw = new QueryWrapper<>();
        qw.eq("task_name", taskName);
        STask one = sTaskService.getOne(qw);
        commonCacheOperator.put(Modules.TASKINAME, taskName);
        commonCacheOperator.put(Modules.TASKID, one.getId());
        System.out.println("name: " + one.getTaskName());
        System.out.println("id: " + one.getId());

        commonCacheOperator.put(Modules.USERID, loginUser.getId());
        return CommonResult.ok();
    }



    /**
     * 实时处理
     *
     * @param str
     */
    @ApiOperationSupport(order = 1)
    @PostMapping("/biz/home/ring/setjsonData")
    public void ring(@RequestBody Object str) {
        //System.out.println(str);
        if (String.valueOf(commonCacheOperator.get(Modules.CHECKSTATUS)).equals(Modules.ON)) {
            SRingData sRingData = new SRingData();
            sRingData.setData(str.toString());
            sRingData.setTime(System.currentTimeMillis());
            sRingData.setCheckId(Long.parseLong(commonCacheOperator.get(Modules.TASKID).toString()));
            sRingData.setUserId(Long.parseLong(commonCacheOperator.get(Modules.USERID).toString()));
            sRingDataService.save(sRingData);
        }
        commonCacheOperator.put("ringTime", System.currentTimeMillis());
        String data = JSONUtil.parseObj(str).getStr("data");
        //if(String.valueOf(commonCacheOperator.get(Modules.CHECKSTATUS)).equals(Modules.ON)){
        ru.checkdata(data);

    }

    @ApiOperationSupport(order = 1)
    @PostMapping("/biz/home/face/export")
    @CrossOrigin
    public void export(@RequestBody SFaceData faceData, HttpServletResponse response) {
        try{
            /**
             * faceReader  数据
             */
            String faceReaderData = facereaderData(faceData);

            /**
             * 手环  数据
             */
            String ringFilePath = ringData(faceData);

            /**
             * 警觉性检验 数据
             */
            String checkpath= checkData(faceData);

            /**
             * 眼动仪数据
             */
            String eyesPath = eyesData(faceData);

            File zipPath = FileUtil.file(FileUtil.getTmpDir() + File.separator + "Simple" + ".zip");

            ZipUtil.zip(zipPath, false,
                    FileUtil.file(faceReaderData),FileUtil.file(checkpath),FileUtil.file(ringFilePath),FileUtil.file(eyesPath));
            // 下载
            CommonDownloadUtil.download(zipPath, response);
        }catch (Exception e){
            e.printStackTrace();
        }



    }












    public String ringData(SFaceData faceData){
        File ring_data = FileUtil.file(FileUtil.getTmpDir() + File.separator + "ring_data" + ".txt");
        QueryWrapper<SRingData> qw = new QueryWrapper<>();
        qw.eq("user_id",faceData.getUserId());
        qw.eq("check_id",faceData.getCheckId());
        List<SRingData> sRingData = sRingDataService.getBaseMapper().selectList(qw);
        if(sRingData.size() == 0){
            BufferedWriter bufWite = null;
            try {
                bufWite = new BufferedWriter(new FileWriter(ring_data));
                bufWite.write("手环暂无数据");
                bufWite.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return FileUtil.getTmpDir() + File.separator + "ring_data" + ".txt";
        }


        try {
            BufferedWriter bufWite = new BufferedWriter(new FileWriter(ring_data));
            for (SRingData sRingDatum : sRingData) {
                bufWite.write(sRingDatum.getData());
                bufWite.write("\\n");
            }
            bufWite.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return FileUtil.getTmpDir() + File.separator + "ring_data" + ".txt";
    }


    @Autowired
    private SEyesDataService sEyesDataService;

    public String eyesData(SFaceData faceData) throws IOException {
        QueryWrapper<SEyesData> qw = new QueryWrapper<>();
        qw.eq("user_id", faceData.getUserId());
        qw.eq("check_id", faceData.getCheckId());
        System.out.println(faceData.getUserId());
        System.out.println(faceData.getCheckId());
        List<SEyesData> sEyesData = sEyesDataService.getBaseMapper().selectList(qw);
        File eyesData = FileUtil.file(FileUtil.getTmpDir() + File.separator + "eyes_data" + ".xlsx");
        Workbook workbook = new XSSFWorkbook();
        if(sEyesData.size() == 0){
            BufferedOutputStream outputStream = FileUtil.getOutputStream(eyesData);
            workbook.write(outputStream);
            outputStream.close();
            return FileUtil.getTmpDir() + File.separator + "eyes_data" + ".xlsx";
        }

        Sheet sheet = workbook.createSheet("Data");
        List<JSONObject> dataList = new ArrayList<>();
        for (SEyesData sEyesDatum : sEyesData) {
            dataList.add(JSONUtil.parseObj(sEyesDatum.getData()));
        }
        // 创建表头
        Row headerRow = sheet.createRow(0);
        if (!dataList.isEmpty()) {
            JSONObject firstObject = dataList.get(0);
            String[] keys = firstObject.keySet().toArray(new String[0]);
            for (int i = 0; i < keys.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(keys[i]);
            }
        }

        // 填充数据
        int rowNum = 1;
        for (JSONObject data : dataList) {
            Row row = sheet.createRow(rowNum++);
            String[] keys = data.keySet().toArray(new String[0]);
            for (int i = 0; i < keys.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(data.getStr(keys[i]));
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入
        BufferedOutputStream outputStream = FileUtil.getOutputStream(eyesData);
        workbook.write(outputStream);
        outputStream.close();

        return FileUtil.getTmpDir() + File.separator + "eyes_data" + ".xlsx";
    }













    public String facereaderData(SFaceData faceData) throws IOException {
        QueryWrapper<SFaceData> qw = new QueryWrapper<>();
        qw.eq("user_id", faceData.getUserId());
        qw.eq("check_id", faceData.getCheckId());
        System.out.println(faceData.getUserId());
        System.out.println(faceData.getCheckId());
        List<SFaceData> sFaceData = faceDataService.getBaseMapper().selectList(qw);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("数据列表");
        File faceReader_data = FileUtil.file(FileUtil.getTmpDir() + File.separator + "faceReader_data" + ".xlsx");
        if (sFaceData.size() == 0) {
            // 写入
            BufferedOutputStream outputStream = FileUtil.getOutputStream(faceReader_data);
            workbook.write(outputStream);
            outputStream.close();
            return FileUtil.getTmpDir() + File.separator + "faceReader_data" + ".xlsx";
        }


        // 添加表头行
        Row headerRow = sheet.createRow(0);
        /*Cell headerCell1 = headerRow.createCell(0);
        headerCell1.setCellValue("编号");
        Cell headerCell2 = headerRow.createCell(1);
        headerCell2.setCellValue("名称");*/

        SFaceData sFaceData1 = sFaceData.get(0);
        String data = sFaceData1.getData();
        JSONArray dataArr = JSONUtil.parseArray(data);
        int cell = 0;
        //表头设置
        for (Object o : dataArr) {
            String str = JSONUtil.parseObj(o).getStr("Label");
            Cell headerCell1 = headerRow.createCell(cell);
            headerCell1.setCellValue(str);
            cell++;
        }
        //内容设置
        for (int i = 0; i < sFaceData.size(); i++) {
            String data1 = sFaceData.get(i).getData();
            JSONArray arr = JSONUtil.parseArray(data1);
            Row dataRow1 = sheet.createRow(i + 1);
            for (int j = 0; j < arr.size(); j++) {
                JSONObject json = JSONUtil.parseObj(arr.get(j));
                Cell dataCell11 = dataRow1.createCell(j);

                try {
                    JSONObject jsonObject = json.getJSONObject(json.getStr("Type"));
                    if (jsonObject.containsKey("float")) {
                        dataCell11.setCellValue(json.getJSONObject(json.getStr("Type")).getStr("float"));
                    }
                    if (jsonObject.containsKey("string")) {
                        dataCell11.setCellValue(json.getJSONObject(json.getStr("Type")).getStr("string"));
                    }

                } catch (Exception e) {
                    //System.out.println(json.getJSONObject(json.getStr("Type")).getStr("string"));
                }
            }
        }

        // 写入
        BufferedOutputStream outputStream = FileUtil.getOutputStream(faceReader_data);
        workbook.write(outputStream);
        outputStream.close();

        return FileUtil.getTmpDir() + File.separator + "faceReader_data" + ".xlsx";
    }


    public String checkData(SFaceData faceData) throws IOException {
        QueryWrapper<SCheckData> qw = new QueryWrapper<>();
        qw.eq("user_id", faceData.getUserId());
        qw.eq("check_id", faceData.getCheckId());
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(faceData.getUserId() + "__监测列表");
        File checkData = FileUtil.file(FileUtil.getTmpDir() + File.separator + "check_data" + ".xlsx");
        List<SCheckData> sCheckData = checkDataService.getBaseMapper().selectList(qw);
        if (sCheckData.size() == 0) {
            BufferedOutputStream outputStream = FileUtil.getOutputStream(checkData);
            workbook.write(outputStream);
            outputStream.close();
            return FileUtil.getTmpDir() + File.separator + "check_data" + ".xlsx";
        }


        // 添加表头行
        SCheckData sCheckData1 = sCheckData.get(0);
        String data = sCheckData1.getData();
        JSONObject entries = JSONUtil.parseObj(data);
        int cell = 0;
        Row headerRow = sheet.createRow(0);
        for (String s : entries.keySet()) {
            Cell headerCell1 = headerRow.createCell(cell);
            headerCell1.setCellValue(s);
            cell++;
        }
        cell = 0;
        for (SCheckData sCheckDatum : sCheckData) {
            Row dataRow1 = sheet.createRow(cell + 1);
            JSONObject entries1 = JSONUtil.parseObj(sCheckDatum.getData());
            int seCell = 0;
            for (String s : entries1.keySet()) {
                String str = entries1.getStr(s);
                Cell dataCell11 = dataRow1.createCell(seCell);
                dataCell11.setCellValue(str);
                seCell++;
            }
            cell++;
        }

        // 写入

        BufferedOutputStream outputStream = FileUtil.getOutputStream(checkData);
        workbook.write(outputStream);
        outputStream.close();
        return FileUtil.getTmpDir() + File.separator + "check_data" + ".xlsx";
    }

  /*  @ApiOperationSupport(order = 1)
    @PostMapping("/biz/home/result/export")
    @CrossOrigin
    public void resultExport(@RequestBody SFaceData faceData, HttpServletResponse response) {
        QueryWrapper<SCheckData> qw = new QueryWrapper<>();
        qw.eq("user_id", faceData.getUserId());
        qw.eq("check_id", faceData.getCheckId());

        List<SCheckData> sCheckData = checkDataService.getBaseMapper().selectList(qw);
        if (BeanUtil.isEmpty(sCheckData)) {
            return;
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(faceData.getUserId() + "__监测列表");
        // 添加表头行

        *//*Cell headerCell1 = headerRow.createCell(0);
        headerCell1.setCellValue("编号");
        Cell headerCell2 = headerRow.createCell(1);
        headerCell2.setCellValue("名称");*//*

        SCheckData sCheckData1 = sCheckData.get(0);
        String data = sCheckData1.getData();
        JSONObject entries = JSONUtil.parseObj(data);
        int cell = 0;
        for (String s : entries.keySet()) {
            Row headerRow = sheet.createRow(0);
            Cell headerCell1 = headerRow.createCell(cell);
            headerCell1.setCellValue(s);
            cell++;
        }
        cell = 0;
        for (SCheckData sCheckDatum : sCheckData) {
            Row dataRow1 = sheet.createRow(cell + 1);
            JSONObject entries1 = JSONUtil.parseObj(sCheckDatum.getData());
            int seCell = 0;
            for (String s : entries1.keySet()) {
                String str = entries1.getStr(s);
                Cell dataCell11 = dataRow1.createCell(seCell);
                dataCell11.setCellValue(str);
                seCell++;
            }
            cell++;
        }


        File resultFile = null;
        try {
            // 生成临时导出文件
            resultFile = FileUtil.file(FileUtil.getTmpDir() + File.separator + "check" + ".xlsx");
            // 写入
            BufferedOutputStream outputStream = FileUtil.getOutputStream(resultFile);
            workbook.write(outputStream);
            outputStream.close();
            // 下载
            CommonDownloadUtil.download(resultFile, response);
        } catch (Exception e) {
        } finally {
            // 删除临时文件

            if (ObjectUtil.isNotEmpty(resultFile)) {
                FileUtil.del(resultFile);
            }
        }
    }*/

    /*   public static void main(String[] args) {
           List<String> strings = ReadFileCon("C:\\Users\\75499\\Desktop\\导出的原始数据示例(1)\\导出的原始数据示例\\手环\\dssPVT.txt");
           List<String> s1 = new ArrayList<>();
           for (int i = 2; i < strings.size() - 2; i++) {
               System.out.println("------------------------------------------------------");
               System.out.println(strings.get(i));
               String replace = strings.get(i).replace("\\[", "").replace("]", "");
               String[] split2 = replace.split("&");
               String[] split3 = split2[3].split(",");
               for (String s : split3) {
                   s1.add(s);
                   System.out.println(s);
               }
               //System.out.println(split3.toString());
           }
           System.out.println(s1.size());

       }*/
//读取文件数据
    private static List<String> ReadFileCon(String filePathName) {
        List<String> strList = new ArrayList<>();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(filePathName));
            String line = reader.readLine();
            while (line != null) {
                strList.add(line);
                line = reader.readLine();// 继续读取下一行
            }
            reader.close();
            return strList;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件不存在");
            return strList;
        }
    }


    //@PostConstruct
    private void test() {
        new Thread(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            List<String> strings = ReadFileCon("C:\\Users\\75499\\Desktop\\导出的原始数据示例(1)\\导出的原始数据示例\\手环\\dssPVT.txt");

            for (int i = 2; i < strings.size() - 2; i++) {
                ru.checkdata(strings.get(i));
                JSONObject entries = new JSONObject();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();

    }

    private void initstart() {
        commonCacheOperator.put("times", "0");
        commonCacheOperator.put(Modules.FACEDEMOBILIZEDCURRENTTIME, "0");
        commonCacheOperator.put(Modules.FACEALARMRESOURT, 0);
        commonCacheOperator.put(Modules.EYESALARMRESOURT, 0);
        commonCacheOperator.put(Modules.RINGALARMRESOURT, 0);
        //初始 监测状态
        commonCacheOperator.put(Modules.CHECKSTATUS, Modules.OFF);

        commonCacheOperator.put(Modules.EYES, Modules.OFF);

        commonCacheOperator.put(Modules.RING, Modules.OFF);

        commonCacheOperator.put(Modules.FACE, Modules.OFF);

        commonCacheOperator.put(Modules.BLINKRATE, 0);
        //闭合眼时间比例
        commonCacheOperator.put(Modules.BLINKTIMERATE, 0);
        //时间总长 1分钟
        commonCacheOperator.put(Modules.BLINKTIMETOTAL, 0);
        //点头
        commonCacheOperator.put(Modules.NODTIMERATE, 0);
        //哈欠
        commonCacheOperator.put(Modules.YAWNTIMERATE, 0);
        //离岗最长时间
        commonCacheOperator.put(Modules.FACEDEMOBILIZEDMAX, 0);
        //离岗次数 /min
        commonCacheOperator.put(Modules.FACEDEMOBILIZEDTIME, 0);
        //默认监测不到人脸
        commonCacheOperator.put(Modules.FACEDEMOBILIZED, 0);


        commonCacheOperator.put(Modules.FACEDEMOBILIZEDTIMELIST, new JSONArray());
        commonCacheOperator.put(Modules.BLINKTIMES, new JSONArray());
        commonCacheOperator.put(Modules.YAWNLIST, new JSONArray());
        commonCacheOperator.put(Modules.NODLIST, new JSONArray());
        commonCacheOperator.put(Modules.HEARTLIST, new JSONArray());

        /*
        *  public static final String x = "x";

    public static final String y = "y";

    public static final String eyeTimes = "eyeTimes";

    public static final String eyeStart = "eyeStart";

    public static final String eyeCount = "eyeCount";*/
        commonCacheOperator.put(Modules.x, 0);

        commonCacheOperator.put(Modules.y, 0);

        commonCacheOperator.put(Modules.eyeTimes, System.currentTimeMillis());

        commonCacheOperator.put(Modules.eyeStart, 0);

        commonCacheOperator.put(Modules.eyeCount, 0);

        commonCacheOperator.put(Modules.eyeletCount, 0);

        commonCacheOperator.put(Modules.eyeletCount, 0);

        commonCacheOperator.put(Modules.eyeletTime, 0);

        commonCacheOperator.put(Modules.FACEDEMOBILIZEDTIME, 0);
        commonCacheOperator.put(Modules.RINGALARMRESOURT, 0);
        commonCacheOperator.put(Modules.EYESALARMRESOURT, 0);
        commonCacheOperator.put(Modules.FACEDEMOBILIZEDMAX, 0);
        commonCacheOperator.put(Modules.FACEDEMOBILIZEDTIME, 0);
        commonCacheOperator.put(Modules.eyeletTimeMin, 0);
        commonCacheOperator.put(Modules.score, 0);
        commonCacheOperator.put("eyesdistance", new JSONArray());
        commonCacheOperator.put("ringTime", 0);
        commonCacheOperator.put("eyesCloseStartTime", 0);
        commonCacheOperator.put("eyesCloseStatus", 0);
        commonCacheOperator.put("eyesClose15time", 0);
        commonCacheOperator.put(Modules.YAWNLISTLOW, new JSONArray());
        commonCacheOperator.put(Modules.YAWNLISTHIGHT, new JSONArray());


    }


}
